package com.egao.common.module.company.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.company.constants.CheckRecordConstants;
import com.egao.common.module.company.constants.CompanyConstants;
import com.egao.common.module.company.constants.MutualConstants;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.CompanyCheckRecord;
import com.egao.common.module.company.entity.Mutual;
import com.egao.common.module.company.entity.vo.MutualApplyFormVO;
import com.egao.common.module.company.entity.vo.MutualApplyListVO;
import com.egao.common.module.company.entity.vo.MutualFormVO;
import com.egao.common.module.company.entity.vo.PreachListVO;
import com.egao.common.module.company.mapper.MutualApplyMapper;
import com.egao.common.module.company.entity.MutualApply;
import com.egao.common.module.company.mapper.MutualMapper;
import com.egao.common.module.company.service.CompanyCheckRecordService;
import com.egao.common.module.company.service.MutualApplyService;
import com.egao.common.module.company.service.PositionService;
import com.egao.common.module.company.utils.CompanyUtil;
import com.egao.common.publicly.entity.ApplyButtonVO;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 双选会申请记录(MutualApply)表服务实现类
 *
 * @author dl
 * @since 2021-02-24 13:52:35
 */
@Service("mutualApplyService")
public class MutualApplyServiceImpl extends ServiceImpl<MutualApplyMapper, MutualApply> implements MutualApplyService {

    @Autowired
    private PositionService positionService;

    @Autowired
    private MutualMapper mutualMapper;

    @Autowired
    private CompanyCheckRecordService companyCheckRecordService;

    @Override
    public List<MutualApplyListVO> listPage(PageParam<MutualApplyListVO> page) {
        if (page.get(MutualConstants.USER_ID) == null) {
            throw new ParameterException("用户不存在");
        }

        Company company = positionService.getCompanyByUserId((Integer) page.get(MutualConstants.USER_ID));
        if (company == null) {
            throw new BusinessException("单位不存在");
        }
        String type = (String) page.get("type");
        // 我的双选会
        if (MutualConstants.TYPE.equals(type)) {
            page.put("companyId", company.getId());
            return baseMapper.listPage(page);
        }
        List<MutualApplyListVO> mutualApplyListVOList = baseMapper.listAllPage(page);
        for (MutualApplyListVO mutualApplyListVO : mutualApplyListVOList) {
            MutualFormVO mutualFormVO = new MutualFormVO();
            mutualFormVO.setId(mutualApplyListVO.getMutualId());
            mutualFormVO.setCreateBy(company.getUserId());
            JsonResult result = applyMutual(mutualFormVO);
            Map<String, Object> map = new HashMap<>(16);
            map.put("applyButton", result.get("applyButton"));
            map.put("cancelButton", result.get("cancelButton"));
            mutualApplyListVO.setButton(map);
        }
        return mutualApplyListVOList;

    }

    @Override
    public Integer getMaxNumberPlate(Integer mutualId) {
        return baseMapper.getMaxNumberPlate(mutualId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveMutualApply(MutualApplyFormVO mutualApplyFormVO) {
        if (mutualApplyFormVO == null) {
            throw new ParameterException("双选会信息编号为空");
        }

        Company company = positionService.getCompanyByUserId(mutualApplyFormVO.getCreateBy());
        if (company == null) {
            throw new BusinessException("单位不存在");
        }

        MutualFormVO mutualFormVO = new MutualFormVO();
        mutualFormVO.setId(mutualApplyFormVO.getMutualId());
        mutualFormVO.setCreateBy(mutualApplyFormVO.getCreateBy());

        JsonResult result = checkMutual(mutualFormVO);
        if (MutualConstants.FAILED.equals(result.getCode())) {
            return result;
        }

        mutualApplyFormVO.setCompanyId(company.getId());

        MutualApply mutualApply = new MutualApply();
        BeanUtil.copyProperties(mutualApplyFormVO, mutualApply);

        mutualApply.setState(MutualConstants.STATE_DSH);

        if (save(mutualApply)) {
            return JsonResult.ok("提交成功");
        }
        return JsonResult.error("提交失败");
    }

    @Override
    public JsonResult checkMutual(MutualFormVO mutualFormVO) {
        if (mutualFormVO == null) {
            throw new ParameterException("双选会信息为空");
        }

        if (mutualFormVO.getId() == null) {
            throw new ParameterException("双选会信息编号为空");
        }

        Mutual mutual = mutualMapper.selectById(mutualFormVO.getId());
        if (mutual == null) {
            throw new BusinessException("双选会信息为空");
        }
        Company company = positionService.getCompanyByUserId(mutualFormVO.getCreateBy());
        if (company == null) {
            throw new BusinessException("无法查询单位信息");
        }

        // 登录
        // 我是否已报名 （是否取消、审核未通过）
        // 是否开放报名
        // 时间
        // 人数

        MutualApply mutualApply = getOne(new QueryWrapper<MutualApply>().eq("company_id", company.getId()).eq("mutual_id", mutualFormVO.getId()).last("limit 1")
                .orderByDesc("create_time"));
        if (mutualApply != null && MutualConstants.INVALID_YES.equals(mutualApply.getInvalid())) {
            return JsonResult.error("报名已取消");
        }

        if (mutualApply != null && MutualConstants.STATE_WTG.equals(mutualApply.getState())) {
            return JsonResult.error("报名审核未通过");
        }

        if (mutualApply != null && MutualConstants.STATE_TG.equals(mutualApply.getState())) {
            return JsonResult.error("已报名");
        }

        if (mutualApply != null && MutualConstants.STATE_DSH.equals(mutualApply.getState())) {
            return JsonResult.error("报名待审核");
        }

        if (MutualConstants.CLOSED.equals(mutual.getOpenFlag())) {
            return JsonResult.error("未开放报名");
        }

        Date today = DateUtil.date();
        if (mutual.getEndTime().before(today)) {
            return JsonResult.error("报名已截止");
        }

        if (mutual.getStartTime().before(today)) {
            return JsonResult.error("双选会已开始");
        }

        int count = count(new QueryWrapper<MutualApply>().eq("state", MutualConstants.STATE_TG).eq("mutual_id", mutualFormVO.getId()));
        if (count == mutual.getCompanyNumber()) {
            return JsonResult.error("报名人数已满");
        }

        return JsonResult.ok("可以报名");
    }

    @Override
    public JsonResult detail(Integer id) {
        if (id == null) {
            throw new ParameterException("双选会报名信息编号为空");
        }

        MutualApply mutualApply = getById(id);
        if (mutualApply == null) {
            throw new BusinessException("双选会报名信息为空");
        }

        MutualApplyFormVO mutualApplyFormVO = new MutualApplyFormVO();
        BeanUtil.copyProperties(mutualApply, mutualApplyFormVO);
        return JsonResult.ok("查询成功").setData(mutualApplyFormVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateMutualApply(MutualApplyFormVO mutualApplyFormVO) {
        MutualApply mutualApply = getMutualApplyFormVO(mutualApplyFormVO);

        mutualApply.setState(MutualConstants.STATE_DSH);

        if (updateById(mutualApply)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult cancelMutualApply(MutualApplyFormVO mutualApplyFormVO) {
        MutualApply mutualApply = getMutualApplyFormVO(mutualApplyFormVO);

        mutualApply.setInvalid(MutualConstants.INVALID_YES);
        mutualApply.setCancelTime(new Date());
        mutualApply.setNumberPlate(null);
        if (updateById(mutualApply)) {
            return JsonResult.ok("取消成功");
        }
        return JsonResult.error("取消失败");
    }

    @Override
    public JsonResult deleteMutualApply(MutualApplyFormVO mutualApplyFormVO) {
        MutualApply mutualApply = getMutualApplyFormVO(mutualApplyFormVO);

        if (removeById(mutualApply)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    private MutualApply getMutualApplyFormVO(MutualApplyFormVO mutualApplyFormVO) {
        if (mutualApplyFormVO == null) {
            throw new ParameterException("双选会申请编号为空");
        }

        if (mutualApplyFormVO.getId() == null) {
            throw new ParameterException("双选会申请编号为空");
        }

        MutualApply mutualApply = getById(mutualApplyFormVO.getId());
        if (mutualApply == null) {
            throw new BusinessException("双选会信息为空");
        }

        BeanUtil.copyProperties(mutualApplyFormVO, mutualApply);
        return mutualApply;
    }

    @Override
    public JsonResult applyMutual(MutualFormVO mutualFormVO) {
        if (mutualFormVO == null) {
            throw new ParameterException("双选会信息为空");
        }

        if (mutualFormVO.getId() == null) {
            throw new ParameterException("双选会信息编号为空");
        }

        Mutual mutual = mutualMapper.selectById(mutualFormVO.getId());
        if (mutual == null) {
            throw new BusinessException("双选会信息为空");
        }

        ApplyButtonVO applyButtonVO = new ApplyButtonVO();
        ApplyButtonVO cancelButtonVO = new ApplyButtonVO();
        cancelButtonVO.setButtonText("取消");

        Company company = positionService.getCompanyByUserId(mutualFormVO.getCreateBy());
        if (company == null) {
            applyButtonVO.setButtonText("非单位不能参加报名");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("单位不存在").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        MutualApply mutualApply = getOne(new QueryWrapper<MutualApply>().eq("company_id", company.getId()).eq("mutual_id", mutualFormVO.getId()));
        if (mutualApply != null && MutualConstants.INVALID_YES.equals(mutualApply.getInvalid())) {
            applyButtonVO.setButtonText("已取消");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("报名已取消").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        if (mutualApply != null && MutualConstants.STATE_WTG.equals(mutualApply.getState())) {
            applyButtonVO.setButtonText("审核未通过");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("报名审核未通过").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        if (mutualApply != null && MutualConstants.STATE_TG.equals(mutualApply.getState())) {
            applyButtonVO.setButtonText("已报名");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(0);
            cancelButtonVO.setMutualApplyId(mutualApply.getId());
            return JsonResult.error("已报名").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO).put("applyId", mutualApply.getId());
        }

        if (mutualApply != null && MutualConstants.STATE_DSH.equals(mutualApply.getState())) {
            applyButtonVO.setButtonText("待审核");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(0);
            cancelButtonVO.setMutualApplyId(mutualApply.getId());
            return JsonResult.error("报名待审核").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO).put("applyId", mutualApply.getId());
        }

        if (MutualConstants.CLOSED.equals(mutual.getOpenFlag())) {
            applyButtonVO.setButtonText("未开放报名");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("未开放报名").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        Date today = DateUtil.date();
//        if (mutual.getStartTime().after(today)) {
//            applyButtonVO.setButtonText("未开始");
//            applyButtonVO.setButtonState(1);
//            cancelButtonVO.setButtonState(2);
//            return JsonResult.error("报名未开始").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
//        }
        if (mutual.getStartTime().before(today)) {
            applyButtonVO.setButtonText("双选会已举办");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("双选会已开始").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        if (mutual.getEndTime().before(today)) {
            applyButtonVO.setButtonText("报名已截止");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("报名已截止").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        int count = count(new QueryWrapper<MutualApply>().eq("state", MutualConstants.STATE_TG).eq("mutual_id", mutualFormVO.getId()));
        if (count == mutual.getCompanyNumber()) {
            applyButtonVO.setButtonText("报名人数已满");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.error("报名人数已满").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        applyButtonVO.setButtonText("报名");
        applyButtonVO.setButtonState(0);
        cancelButtonVO.setButtonState(2);
        return JsonResult.ok("可以报名").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
    }

    @Override
    public JsonResult countMutual(PageParam<MutualApplyListVO> page) {
        // 举办时间
        page = (PageParam<MutualApplyListVO>) CompanyUtil.putApplyTime(page);
        page.setSearchCount(false);
        page.setSize(100);
        Map<String, Object> map = new HashMap<>(5);
        Integer total = baseMapper.countTotal(page);
        page.getPageData().put("state", CompanyConstants.COMPANY_STATE_PASS);
        page.getPageData().put("invalid", MutualConstants.INVALID_NO);
        Integer totalCompany = baseMapper.countTotalCompany(page);
        List<Map<String, Object>> provinceList = baseMapper.countProvince(page);
        List<Map<String, Object>> natureList = baseMapper.countNature(page);
        List<Map<String, Object>> industryList = baseMapper.countIndustry(page);
        List<Map<String, Object>> scaleList = baseMapper.countScale(page);
        map.put("total", total);
        map.put("totalCompany", totalCompany);
        map.put("provinceList", provinceList);
        map.put("natureList", natureList);
        map.put("industryList", industryList);
        map.put("scaleList", scaleList);
        return JsonResult.ok().setData(map);
    }

    @Override
    public JsonResult resetCancel(Integer id, Integer loginUserId) {
        MutualApply mutualApply = baseMapper.selectById(id);
        if (mutualApply == null) {
            throw new BusinessException("参数异常");
        }

        mutualApply.setInvalid(MutualConstants.INVALID_NO);
        mutualApply.setNumberPlate(null);
        mutualApply.setState(MutualConstants.STATE_DSH);

        if (updateById(mutualApply)) {
            // 记录
            CompanyCheckRecord companyCheckRecord = new CompanyCheckRecord();
            companyCheckRecord.setCompanyId(mutualApply.getCompanyId());
            companyCheckRecord.setState(mutualApply.getState());
            companyCheckRecord.setStateContent("重置单位取消");
            companyCheckRecord.setCheckUserId(loginUserId);
            companyCheckRecord.setType(CheckRecordConstants.CHECK_MUTUAL);
            companyCheckRecord.setBusinessId(mutualApply.getId());
            companyCheckRecordService.save(companyCheckRecord);

            return JsonResult.ok("重置成功");
        }

        return JsonResult.error("重置失败");
    }
}